<template>
  <div class="ver-layout app-container">
    <div class="amap-wrapper">
      <el-amap class="amap-box" vid="amap-vue" :amap-manager="amapManager" :events="events" :zoom="9"/>
    </div>
    <div class="hor-layout-center-all bottom-layout">
      <el-button type="warning" size="mini" @click="resetCenter">重置中心</el-button>
      <el-button type="primary" size="mini" :disabled="!canStartUse" @click="startNavi">开始</el-button>
      <el-button type="primary" size="mini" :disabled="!canPauseUse" @click="pauseNavi">暂停</el-button>
      <el-button type="primary" size="mini" :disabled="!canResumeUse" @click="resumeNavi">继续</el-button>
      <el-button type="primary" size="mini" :disabled="!canStopUse" @click="stopNavi">停止</el-button>
    </div>
    <el-form inline class="time-select-form">
      <el-form-item label="选择开始时间">
        <el-select size="small" v-model="lineObj.startTime" @change="selectTime" placeholder="请选择">
          <el-option
              v-for="item in startTimeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择结束时间">
        <el-select size="small" v-model="lineObj.endTime" @change="selectTime" placeholder="请选择">
          <el-option
              v-for="item in endTimeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="time-container">
      <time-slider ref="timeSlider" :startTime="lineObj.startTime"
                   :endTime="lineObj.endTime" :timeList="lineObj.timeList"
                   @changeValue="timeChanged" @timerFinish="stopNavi"></time-slider>
    </div>
  </div>
</template>

<script>
import {route1} from "./413966181";
import {getStampBySpan, rTime, rTimeStamp} from "@/utils/util.js"
import {AMapManager, lazyAMapApiLoaderInstance} from 'vue-amap'
import TimeSlider from "@/components/time-slider/time-slider"

export default {
  name: "playback",
  components: {
    TimeSlider
  },
  data() {
    let _this = this;
    let amapManager = new AMapManager() // 新建生成地图画布
    let {name, arrTrack} = route1.data
    let routeObj = {name, arrTrack}
    return {
      routeObj,
      lineObj: {
        timeList: [],
        startTime: '',
        endTime: '',
        currentTime: 0
      },
      events: {
        init() {
          lazyAMapApiLoaderInstance.load().then(() => {
            // _this.initMarker()
            _this.initLine()
            _this.initDistance()
          })
        }
      },
      amapManager,
      metaDataMap: '',
      navigator: '',//巡航器
      navigatorState: 0,//状态
      pathSimplifierIns: '',//轨迹展示组件
    }
  },
  computed: {
    startTimeOptions() {
      let {startTime, endTime} = this.lineObj
      let index = this.lineObj.timeList.findIndex(item => item.label == endTime)
      console.log("startTimeOptions", index)
      return this.lineObj.timeList.filter(item => item.value < index)
    },
    endTimeOptions() {
      let {startTime, endTime} = this.lineObj
      let index = this.lineObj.timeList.findIndex(item => item.label == startTime)
      console.log("endTimeOptions", index)
      return this.lineObj.timeList.filter(item => item.value > index)
    },
    canStartUse() {
      return this.navigatorState == 0 || this.navigatorState == 4
    },
    canPauseUse() {
      return this.navigatorState == 1 || this.navigatorState == 3
    },
    canResumeUse() {
      return this.navigatorState == 2
    },
    canStopUse() {
      return this.navigatorState == 1 || this.navigatorState == 2 || this.navigatorState == 3
    }
  },
  mounted() {
    let {name, arrTrack} = this.routeObj
    this.lineObj.startTime = rTime(arrTrack[0].time)
    this.lineObj.endTime = rTime(arrTrack[arrTrack.length - 1].time)
    this.lineObj.timeList = arrTrack.map((item, index) => {
      return {label: rTime(item.time), value: index, lnglat: item.lnglat}
    })
  },
  methods: {
    initLine() {
      this.metaDataMap = this.amapManager.getMap()
      AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], (PathSimplifier, $) => {
        if (!PathSimplifier.supportCanvas) {
          alert('当前环境不支持 Canvas！');
          return;
        }
        this.createNavigator(PathSimplifier)
      });
    },
    initDistance() {
      let disObj = {}, timeList = this.lineObj.timeList
      for (let i = 0; i < timeList.length - 1; i++) {
        let p1 = timeList[i].lnglat
        let p2 = timeList[i + 1].lnglat
        let dis = AMap.GeometryUtil.distance(p1, p2);//这个距离单位是：m
        disObj[timeList[i].label] = dis
      }
      console.log("initDistance", disObj)
      this.lineObj.timeList = this.lineObj.timeList.map(item => {
        item.dis = disObj[item.label]
        return item
      })
      console.log("initDistance", this.lineObj.timeList)
    },
    createNavigator(PathSimplifier) {
      this.pathSimplifierIns = new PathSimplifier({
        zIndex: 100,
        //autoSetFitdiv:false,
        map: this.metaDataMap, //所属的地图实例
        getPath: function (pathData, pathIndex) {
          return pathData.path;
        },
        getHoverTitle: function (pathData, pathIndex, pointIndex) {
          if (pointIndex >= 0) {
            //point
            return pathData.name + '，点：' + pointIndex + '/' + pathData.path.length;
          }
          return pathData.name + '，点数量' + pathData.path.length;
        },
        renderOptions: {
          "keyPointTolerance": 0,
          renderAllPointsIfNumberBelow: 100, //绘制路线节点，如不需要可设置为-1
          //轨迹线的样式
          pathLineStyle: {
            lineWidth: 4,
            strokeStyle: '#cfa454',
            borderWidth: 1,
            borderStyle: "#cccccc",
            dirArrowStyle: true
          },
          pathLineSelectedStyle: {
            lineWidth: 5,
            strokeStyle: "#C11534",
            borderWidth: 1,
            borderStyle: "#cccccc",
            dirArrowStyle: true
          },
          dirArrowStyle: {
            stepSpace: 35,
            strokeStyle: "#ffffff",
            lineWidth: 2
          },
        }
      });

      //设置数据
      let route_path = this.routeObj.arrTrack.map(item => item.lnglat)
      this.pathSimplifierIns.setData([{name: '路线0', path: route_path}]);
      //对第一条线路（即索引 0）创建一个巡航器
      this.navigator = this.pathSimplifierIns.createPathNavigator(0, {loop: false, speed: 200});
      this.navigator.on('move', (data, position) => {
        // console.log("move=-=-=-=-=-=-=-=-=-=-=-=-=-=", data, position)
      });
    },
    selectTime(val) {
      this.stopNavi()
      let startIndex = this.lineObj.timeList.findIndex(item => item.label == this.lineObj.startTime)
      let endIndex = this.lineObj.timeList.findIndex(item => item.label == this.lineObj.endTime)
      let route_path = this.routeObj.arrTrack.slice(startIndex, endIndex + 1).map(item => item.lnglat);
      this.pathSimplifierIns.setData([{name: '路线0', path: route_path}]);
      this.navigator = this.pathSimplifierIns.createPathNavigator(0, {loop: false, speed: 200});
      this.navigator.on('move', (data, position) => {
        // console.log("move=-=-=-=-=-=-=-=-=-=-=-=-=-=", data, position)
        if (position.tail == 0) this.navigatorState = 0
      });
    },
    timeChanged(span, percent) {
      console.log("timeChanged", span, percent)
      this.navigator.moveToPoint(span, percent)
      if (this.navigatorState == 1 || this.navigatorState == 2) this.pauseNavi()
    },
    resetCenter() {
      let center = [117.199002, 39.132733]
      this.metaDataMap.setCenter(center); //设置地图中心点
      this.metaDataMap.setZoom(16);
    },
    startNavi() {
      this.navigatorState = 1
      this.navigator.start();
      this.$refs.timeSlider.startTimer()
    },
    pauseNavi() {
      this.navigatorState = 2
      this.navigator.pause()
      this.$refs.timeSlider.pauseTimer()
    },
    resumeNavi() {
      this.navigatorState = 3
      this.navigator.resume()
      this.$refs.timeSlider.resumeTimer()
    },
    stopNavi() {
      this.navigatorState = 4
      this.navigator.stop()
      this.$refs.timeSlider.stopTimer()
    },
    initMarker() {
      let name = 'marker', value = '123'
      AMapUI.loadUI(['overlay/SimpleMarker'], function (SimpleMarker) {
        new SimpleMarker({
          zIndex: 50,
          iconLabel: '<div class="mapIcon" style=""><span class="mapIcon_title">' + name + '</span><span class="mapIcon_num">' + value + '</span></div>',
          //直接设置html(需要以"<"开头并且以">"结尾)
          iconStyle: '',
          //设置基点偏移
          offset: new AMap.Pixel(-10, -60), // 偏移
          map: this.metaDataMap,
          showPositionPoint: true, // 定位点
          position: [121.5273289, 31.21515049]
        })
      })
    },
  }
}
</script>

<style scoped>
.app-container {
  width: 100%;
  padding: 10px;
  overflow: hidden;
  height: calc(100vh - 40px - 20px - 30px);
}

.amap-wrapper {
  width: 100%;
  flex: 1;
}

.time-select-form {
  width: fit-content;
  margin: auto;
  margin-bottom: 10px;
}

/deep/ .time-select-form > .el-form-item {
  margin-bottom: 0px;
}

.time-container {
  width: calc(100% - 10 * 4px);
  margin: 0px 10px;
  background: lightgrey;
  padding: 3px 10px;
  padding-bottom: 10px;
  border-radius: 3px;
}

.bottom-layout {
  margin: 10px 20px;
}
</style>
